package com.ruoyi.project.modules.usage.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.project.modules.business.domain.BusinessInfo;
import com.ruoyi.project.modules.business.service.IBusinessInfoService;
import com.ruoyi.project.modules.businessSystem.domain.BusinessSystem;
import com.ruoyi.project.modules.businessSystem.service.IBusinessSystemService;
import com.ruoyi.project.modules.businessUsage.domain.BusinessUsage;
import com.ruoyi.project.modules.businessUsage.service.IBusinessUsageService;
import com.ruoyi.project.modules.category.domain.Category;
import com.ruoyi.project.modules.category.service.ICategoryService;
import com.ruoyi.project.modules.fileInfo.domain.FileInf;
import com.ruoyi.project.modules.fileInfo.service.IFileInfoService;
import com.ruoyi.project.modules.interfaceObject.domain.InterfaceObject;
import com.ruoyi.project.modules.interfaceObject.service.IInterfaceObjectService;
import com.ruoyi.project.modules.interfaceinfo.domain.InterfaceInfo;
import com.ruoyi.project.modules.interfaceinfo.service.IInterfaceInfoService;
import com.ruoyi.project.modules.page.domain.Page;
import com.ruoyi.project.modules.page.service.IPageService;
import com.ruoyi.project.modules.role.domain.ParticipateRole;
import com.ruoyi.project.modules.role.service.IParticipateRoleService;
import com.ruoyi.project.modules.table.domain.TableInfo;
import com.ruoyi.project.modules.tableObject.domain.TableObject;
import com.ruoyi.project.modules.tableObject.service.ITableObjectService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.project.modules.usage.domain.Usage;
import com.ruoyi.project.modules.usage.service.IUsageService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用况Controller
 *
 * @author smallrain
 * @date 2021-11-04
 */
@Controller
@RequestMapping("/usage/usage")
public class UsageController extends BaseController {
    private String prefix = "usage/usage";

    @Autowired
    private IUsageService usageService;

    @RequiresPermissions("usage:usage:view")
    @GetMapping()
    public String usage() {
        return prefix + "/usage";
    }

    /**
     * 查询用况列表
     */
    @RequiresPermissions("usage:usage:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Usage usage) {
        startPage();
        usage.setUserId(ShiroUtils.getSysUser().getUserId());
        usage.setFlag(this.getFlag());
        List<Usage> list = usageService.selectUsageList(usage);
        return getDataTable(list);
    }

    /**
     * 导出用况列表
     */
    @RequiresPermissions("usage:usage:export")
    @Log(title = "用况", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Usage usage) {
        List<Usage> list = usageService.selectUsageList(usage);
        ExcelUtil<Usage> util = new ExcelUtil<Usage>(Usage.class);
        return util.exportExcel(list, "用况数据");
    }

    @Autowired
    private IParticipateRoleService participateRoleService;

    @Autowired
    private IInterfaceInfoService interfaceInfoService;

    @Autowired
    private IInterfaceObjectService interfaceObjectService;

    /**
     * 新增用况
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        ParticipateRole participateRole = new ParticipateRole();
        List<ParticipateRole> participateRoles = this.participateRoleService.selectParticipateRoleList(participateRole);
        mmap.put("participateRoles", participateRoles);
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setFbType("2");
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        mmap.put("interfaceInfoList", interfaceInfoList);
        return prefix + "/add";
    }

    /**
     * 新增保存用况
     */
    @RequiresPermissions("usage:usage:add")
    @Log(title = "用况", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Usage usage) {
        return toAjax(usageService.insertUsage(usage));
    }

    @Autowired
    private ICategoryService categoryService;

    /**
     * 修改用况
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Usage usage = usageService.selectUsageById(id);
        List<ParticipateRole> participateRoles = this.participateRoleService.selectParticipateRoleList(new ParticipateRole());
        if (usage != null) {
            Category category = this.categoryService.selectCategoryById(usage.getCategoryId());
            if (category != null) {
                usage.setCategoryName(category.getCategoryName());
            }
        }

        List<ParticipateRole> participateRoleList = this.participateRoleService.selectParticipateRoleListByUsageId(id);
        if (CollectionUtil.isNotEmpty(participateRoles)) {
            if (CollectionUtil.isNotEmpty(participateRoles)) {
                for (ParticipateRole usage1 : participateRoles) {
                    for (ParticipateRole role : participateRoleList) {
                        if (usage1.getId().equals(role.getId())) {
                            usage1.setFlag(true);
                        }
                    }
                }
            }
        }
        mmap.put("participateRoles", participateRoles);
        mmap.put("usage", usage);

        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setFbType("2");
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        mmap.put("interfaceInfoList", interfaceInfoList);
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectId(id);
        interfaceObject.setObjectType("3");
        List<InterfaceObject> interfaceObjects = interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isNotEmpty(interfaceObjects)) {
            usage.setInterfaceId(interfaceObjects.get(0).getInterfaceId());
        }

        mmap.put("usage", usage);
        return prefix + "/edit";
    }

    /**
     * 修改保存用况
     */
    @RequiresPermissions("usage:usage:edit")
    @Log(title = "用况", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Usage usage) {
        return toAjax(usageService.updateUsage(usage));
    }

    @Autowired
    private IBusinessUsageService businessUsageService;

    /**
     * 删除用况
     */
    @RequiresPermissions("usage:usage:remove")
    @Log(title = "用况", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(usageService.deleteUsageByIds(ids));
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        Usage usage = this.usageService.selectUsageById(id);
        mmap.put("usage", usage);
        if (usage != null) {
            Category category = this.categoryService.selectCategoryById(usage.getCategoryId());
            if (category != null) {
                usage.setCategoryName(category.getCategoryName());
            }
        }
        List<ParticipateRole> participateRoles = this.participateRoleService.selectParticipateRoleList(new ParticipateRole());

        List<ParticipateRole> participateRoleList = this.participateRoleService.selectParticipateRoleListByUsageId(id);
        StringBuilder roleNames = new StringBuilder();
        if (CollectionUtil.isNotEmpty(participateRoles)) {
            if (CollectionUtil.isNotEmpty(participateRoles)) {
                for (ParticipateRole usage1 : participateRoles) {
                    for (ParticipateRole role : participateRoleList) {
                        if (usage1.getId().equals(role.getId())) {
                            roleNames.append(usage1.getRoleName()).append(",");
                        }
                    }
                }
                if (roleNames.length() > 1) {
                    mmap.put("roleNames", roleNames.substring(0, roleNames.length()-1));
                }
            }
        }

        mmap.put("usage", usage);
        return prefix + "/details";
    }

    @Autowired
    private IBusinessInfoService businessInfoService;

    @PostMapping("/businessList")
    @ResponseBody
    public AjaxResult businessList(@RequestParam Long usageId) {
        BusinessUsage businessUsage = new BusinessUsage();
        businessUsage.setUsageId(usageId);
        List<BusinessUsage> businessUsages = this.businessUsageService.selectBusinessUsageList(businessUsage);
        if (CollectionUtil.isNotEmpty(businessUsages)) {
            Set<Long> businessIds = businessUsages.stream().map(BusinessUsage::getBusinessId).collect(Collectors.toSet());
            BusinessInfo businessInfo = new BusinessInfo();
            businessInfo.setBusinessInfoIds(businessIds);
            List<BusinessInfo> businessInfos = this.businessInfoService.selectBusinessInfoList(businessInfo);
            return AjaxResult.success(businessInfos);
        }
        return AjaxResult.success(new ArrayList<BusinessInfo>());
    }
    @Autowired
    private IPageService pageService;
    @Autowired
    private IFileInfoService fileInfoService;

    /**
     * 关联页面
     * @param usageId id
     * @return
     */
    @PostMapping("/pageList")
    @ResponseBody
    public AjaxResult pageList(@RequestParam Long usageId) {
        Long interfaceId = this.getInterfaceId(usageId);
        if (interfaceId != null) {
            InterfaceObject interfaceObject = new InterfaceObject();
            interfaceObject.setInterfaceId(interfaceId);
            interfaceObject.setObjectType("2");
            List<InterfaceObject> interfaceObjectList = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject);
            if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
                Set<Long> pageIds = interfaceObjectList.stream().map(InterfaceObject::getObjectId).collect(Collectors.toSet());
                Page page = new Page();
                page.setPageIds(pageIds);
                List<Page> pageList = this.pageService.selectPageList(page);
                return AjaxResult.success(pageList);
            }
        }

        return AjaxResult.success(new ArrayList<Page>());
    }

    private Long getInterfaceId(Long usageId) {
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectId(usageId);
        interfaceObject.setObjectType("3");
        List<InterfaceObject> interfaceObjectList = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
            return interfaceObjectList.get(0).getInterfaceId();
        }
        return null;
    }

    @Autowired
    private IBusinessSystemService businessSystemService;

    @Autowired
    private ITableObjectService tableObjectService;

    /**
     * 关联业务系统
     * @param usageId id
     * @return
     */
    @PostMapping("/businessSystemList")
    @ResponseBody
    public AjaxResult businessSystemList(@RequestParam Long usageId) {
        List<BusinessSystem> businessSystems = new ArrayList<>();
        Long interfaceId = this.getInterfaceId(usageId);
        if (interfaceId != null) {
            List<TableInfo> tableInfos = this.interfaceInfoService.tableList("2", interfaceId);
            if (CollectionUtil.isNotEmpty(tableInfos)) {
                Set<Long> tableIds = tableInfos.stream().map(TableInfo::getId).collect(Collectors.toSet());
                TableObject tableObject = new TableObject();
                tableObject.setObjectType("1");
                tableObject.setTableIds(tableIds);
                List<TableObject> tableObjects = this.tableObjectService.selectTableObjectList(tableObject);
                if (CollectionUtil.isNotEmpty(tableObjects)) {
                    Set<Long> businessSystemIds = tableObjects.stream().map(TableObject::getObjectId).collect(Collectors.toSet());
                    BusinessSystem businessSystem = new BusinessSystem();
                    businessSystem.setBusinessSystemIds(businessSystemIds);
                    businessSystems = businessSystemService.selectBusinessSystemList(businessSystem);
                }
            }
        }
        return AjaxResult.success(businessSystems);
    }

    @PostMapping("/bffInfo")
    @ResponseBody
    public AjaxResult bffInfo(@RequestParam Long usageId) {
        Long interfaceId = this.getInterfaceId(usageId);
        if (interfaceId != null) {
            InterfaceInfo interfaceInfo = this.interfaceInfoService.selectInterfaceInfoById(interfaceId);
            return AjaxResult.success(interfaceInfo);
        }
        return AjaxResult.success(null);
    }
}
